package com.vbobot.demo.spring.mvc;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Bobo
 * @date 2023/9/20
 */
@RestController
@RequestMapping
@SpringBootApplication
public class SpringDemoMvcApplication {
    public static void main(String[] args) {
        new SpringApplicationBuilder(SpringDemoMvcApplication.class).web(WebApplicationType.SERVLET).run(args);
    }

    @RequestMapping({"/redirect/**", "/forward"})
    public String redirect(@RequestBody(required = false) JsonNode jsonNode, @RequestParam(required = false) Map<String, String> params, HttpServletRequest request) throws JsonProcessingException {
        System.out.println("body:" + jsonNode);
        System.out.println("params:" + params);
        final String uri = request.getRequestURI();
        System.out.println("uri:" + uri);
        final ObjectMapper objectMapper = new ObjectMapper();
        final ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.set("body", jsonNode);
        objectNode.putPOJO("params", params);
        objectNode.put("uri", uri);
        return objectMapper.writeValueAsString(objectNode);
    }
}
